'use strict'

let config = require('../../config');
let errors = config.errors;

let util = require('util');
let models = require('../models');
let Session = require('./session');

let UserDao = models.UserDao;
let IFlyTokens = {};

function filter(req, res, next) {
    if ( req.originalUrl.indexOf('dispatch') == -1 ) {
        next();
        return;
    }

    console.log('token: ' + req.cookies.token);
    if ( !isIFlyToken(req, res) ) {
        if ( 'token' in req.query && Session.isValid(req.query.token) ) {
            next();
            return;
        }
        if ( 'token' in req.cookies && Session.isValid(req.cookies.token) ) {
            next();
            return;
        }
    }
    else {
        console.log('is ifly token');
    }
    
    if ( !('successful' in req.query) ) {
        let url = util.format('http://%s%s', config.server.host, req.originalUrl);
        let encodedUrl = encodeURIComponent(url);
        console.log(encodedUrl);
        
        let destination = util.format('http://%s/attendance_cas/user?redirect=%s',
                config.server.cas.host, encodedUrl);
        console.log(destination);

        let nextPage = encodeURIComponent(destination);
        console.log(nextPage);

        let finalUrl = util.format('http://%s/attendance_cas/login.jsp?nextpage=%s',
                config.server.cas.host, nextPage);

        res.redirect(finalUrl);
        return;
    }
    // 如果有成功参数但是失败，需要登录
    else if ( req.query.successful == 'false' ) {
        console.log(req.query.successful);
        res.send('Need to login');

        return;
    }
    // 如果有成功参数且成功，获取用户名，登录
    else if ( req.query.successful == 'true' ) {
        let userName = req.query.cas_user;

        let user = UserDao.findOne({
            name: userName,
        });

        if ( !user ) {
            res.json({
                successful: false,
                error: errors.NoUser
            });
            return;
        }

        let token = Session.newToken(req, user);
        req.session.login = {
            user: user
        };

        req.query.token = token;
        console.log('new token: ' + token);
        IFlyTokens[token] = 1;
        res.cookie('token', token, {
            maxAge: config.params.user.token.expired * 60 * 1000
        });

        next();
    }
}

function isIFlyToken(req, res) {
    let token = null;
    if ( 'token' in req.query ) {
        token = req.query.token;
    }
    if ( 'token' in req.cookies ) {
        token = req.cookies.token;
    }

    if ( !token ) {
        return false;
    }

    if ( token in IFlyTokens ) {
        delete IFlyTokens[token];
        res.clearCookie('token');
        return true;
    }

    return false;
}

module.exports = {
    filter
};
